<template>
  <div class="meetingEdit">
    <div class="meetingEdit-title">
      会议新增
    </div>
    <el-form ref="form" :model="form" label-width="100px" :rules="rules">
      <el-form-item label="会议名称" prop="name">
        <el-input v-model="form.name" clearable size="small"></el-input>
      </el-form-item>
      <el-form-item label="创建分会场" prop="places">
        <el-input v-model="form.region" style="width: 82%;margin-right: 20px" clearable size="small"></el-input>
        <el-button type="primary" size="small" icon="el-icon-plus" style="flex: 1" @click="handleClickAddTag">添加分会场</el-button>
        <el-tag
          class="meetingEdit-tag"
          v-for="(tag, index) in form.places"
          :key="index"
          closable
          @close="handleClose(tag)"
          type="info">
          <span>{{tag}}</span>
        </el-tag>
      </el-form-item>
      <el-form-item label="会议时间" prop="startTime">
        <el-row>
          <el-col :span="11">
            <div>开始时间</div>
            <el-date-picker type="date" placeholder="选择日期" v-model="form.startTime" value-format="timestamp" style="width: 100%;" size="small"></el-date-picker>
          </el-col>
          <el-col :span="11" :offset="2">
            <div>结束时间</div>
            <el-date-picker type="date" placeholder="选择日期" v-model="form.endTime" value-format="timestamp" style="width: 100%;" size="small"></el-date-picker>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="报名截止时间">
        <el-date-picker type="datetime" placeholder="选择日期" v-model="form.signupDeadline" value-format="timestamp" style="width: 100%;" size="small"></el-date-picker>
      </el-form-item>
      <el-form-item label="会议地点" prop="location">
        <el-input v-model="form.location" size="small"></el-input>
      </el-form-item>
      <el-form-item label="主办方" prop="tags">
        <el-select v-model="form.organizerList" placeholder="请选择主办方" style="width: 70%;margin-right: 20px" clearable @change="handleChangeSponsor">
          <el-option
            v-for="dict in organizerList"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
        <el-button type="primary" size="small" icon="el-icon-plus" style="width: 120px" @click="handleClickAddSponsorTag">添加主办方</el-button>
        <el-button type="primary" size="small" icon="el-icon-tickets" style="flex: 1" @click="handleClickSponsorList">主办方列表</el-button>
        <el-tag
          class="meetingEdit-tag"
          v-for="tag in form.tags"
          :key="tag.name"
          closable
          @close="handleClose2(tag)"
          type="info">
          <span>{{tag.name}}</span>
        </el-tag>
      </el-form-item>
      <el-form-item label="微信分享图片">
        <el-row>
          <el-col :span="14">
            <el-upload
              :action="uploadImgUrl"
              list-type="picture-card"
              :multiple="false"
              :limit="1"
              :headers="headers"
              :file-list="fileList"
              :before-upload="beforeUpload"
              :on-success="handleUploadSuccess"
              :on-remove="handleRemove">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-col>
          <el-col :span="10">
            <div>温馨提示：</div>
            <div>此图片将作为微信分享或报名推送时的缩略图。建议上传尺寸 <span style="color: red">400px*400px</span>的.png、.jpg、.gif图片，图片小于3M</div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="会议海报">
        <el-row>
          <el-col :span="14">
            <el-upload
              :action="uploadImgUrl"
              list-type="picture-card"
              :multiple="false"
              :limit="1"
              :headers="headers"
              :file-list="fileList2"
              :before-upload="beforeUpload2"
              :on-success="handleUploadSuccess2"
              :on-remove="handleRemove2">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-col>
          <el-col :span="10">
            <div>温馨提示：</div>
            <div>此图片将作为此会议的封面，一张漂亮的封面图片可以提高浏览者视觉体验，同时可以宣传会议内容。建议上传尺寸 <span style="color: red">1920px*520px</span> 的.png、.jpg、.gif图片，图片小于3M</div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="会议分类" prop="category">
        <el-select v-model="form.category" placeholder="请选择会议分类" style="width: 100%;">
          <el-option v-for="dict in dict.type.sys_meeting_sort" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="前台显示主题">
        <el-radio-group v-model="form.showTheme">
          <el-radio
            v-for="dict in dict.type.sys_show_theme"
            :key="dict.value"
            :label="dict.value"
          >{{dict.label}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="会议详情" prop="summary">
        <Editor v-model="form.summary" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即创建</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
    <DialogSponsor :visible.sync="sponsorVisible" @refresh="getOrganizerList" />
    <DialogList ref="dialogList" :visible.sync="listVisible" @refresh="getOrganizerList" @editFun="handleEditFun" />
  </div>
</template>
<script>
import Editor from "@/components/Editor/index";
import DialogSponsor from './components/DialogSponsor'
import DialogList from './components/DialogList'
import {getOrganizer, listOrganizer} from '@/api/meetingManagement/organizer'
import { getToken } from "@/utils/auth";
import {updateMeet, getMeet} from "@/api/meetingManagement/meet";
export default {
  name: 'MeetingEdit',
  components: {
    Editor,
    DialogSponsor,
    DialogList
  },
  dicts: ['sys_show_theme', 'sys_yes_no_num', 'sys_meeting_sort'],
  data() {
    return {
      form: {
        name: '',
        places: [],
        region: '',
        startTime: '',
        endTime: '',
        signupDeadline: '',
        location: '',
        type: [],
        showTheme: '',
        organizerList: [],
        tags: [],
        wechatShareImg: null,
        coverImg: null,
        category: null,
        summary: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入会议名称', trigger: 'blur' }
        ],
        places: [
          { type: 'array', required: true, message: '请输入分会场', trigger: 'change' }
        ],
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择结束时间', trigger: 'change' }
        ],
        signupDeadline: [
          { required: true, message: '请选择报名截止时间', trigger: 'change' }
        ],
        location: [
          { required: true, message: '请输入会议地点', trigger: 'blur' }
        ],
        tags: [
          { type: 'array', required: true, message: '请选择主办方', trigger: 'change' }
        ],
        category: [
          { required: true, message: '请选择会议分类', trigger: 'change' }
        ],
        summary: [
          { required: true, message: '请输入会议详情', trigger: 'blur' }
        ]
      },
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      uploadImgUrl: process.env.VUE_APP_BASE_API + '/common/upload', // 上传的图片服务器地址
      fileList: [],
      fileList2: [],
      dialogVisible: null,
      dialogImageUrl: '',
      sponsorVisible: false,
      listVisible: false,
      organizerList: []
    }
  },
  created() {
    const id = this.$route.params && this.$route.params.id
    console.log("111111111111111111111111111",id)
    this.getDetail(id)
    this.getOrganizerList();
  },
  methods: {
    getDetail(id) {
      getMeet(id).then(res => {
        if (res.code === 200) {
          this.form = res.data
        }
      })
    },
    handleEditFun(row) {
      getOrganizer(row.id).then(res => {
        if (res.code === 200) {
          this.printData = res.data;
          this.sponsorVisible = true;
        }
      })
    },
    getOrganizerList() {
      listOrganizer().then(res => {
        if (res.code === 200) {
          this.organizerList = res.rows;
          if (this.form.organizerIds) {
            // 提前分割并转为 Set，提高查找效率
            const selectedIds = new Set(this.form.organizerIds.split(','));

            // 单次遍历，O(n) 复杂度
            this.form.tags = this.organizerList.filter(item =>
              selectedIds.has(String(item.id))
            );
          }

          console.log("2222222222",this.form.tags);
        }
      })
    },
    handleCancel() {
      const obj = { path: "/meetingManagement/activity" }
      this.$tab.closeOpenPage(obj)
    },
    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.organizerIds = this.form.tags.map(tag => tag.id).join(',')
          console.log('submit!', this.form);
          updateMeet(this.form).then(res => {
            if (res.code === 200) {
              this.$message.success(res.msg || '修改成功');
              const obj = { path: "/meetingManagement/activity" }
              this.$tab.closeOpenPage(obj)
            }
          })
        }
      });
    },
    handleClose(tag) {
      this.form.places.splice(this.form.places.indexOf(tag), 1);
    },
    handleClose2(tag) {
      this.form.tags.splice(this.form.tags.indexOf(tag), 1);
    },
    handleClickAddTag() {
      if (!this.form.region) {
        this.$message.error('请输入分会场');
        return;
      }
      this.form.places.push(this.form.region);
      this.form.region = '';
    },
    handleChangeSponsor(val, data) {
      if (val) {
        const isExist = this.form.tags.some(tag => tag.id === val);
        if (isExist) {
          this.$message.warning('该项已存在');
          return;
        }
        let item = this.organizerList.filter(item => item.id === val);
        this.form.tags.push(...item);
        this.form.organizerList = []
      }
    },
    handleClickAddSponsorTag() {
      this.sponsorVisible = true;
    },
    handleClickSponsorList() {
      this.listVisible = true;
      this.$refs.dialogList.initData();
    },
    beforeUpload(file) {
      console.log(file, 'file');
      let imageUrl = URL.createObjectURL(file);
      const isJPG = file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/gif';
      const isLt2M = file.size / 1024 / 1024 < 3;
      let isHeight = imageUrl.width === 400 && imageUrl.height === 400;
      if (!isJPG) {
        this.$message.error('上传图片只能是 png/JPG/gif 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 3MB!');
      }
      if (!isHeight) {
        this.$message.error('上传图片尺寸必须为 400px*400px!');
      }
      return isJPG && isLt2M && isHeight;
    },
    handleRemove() {
      this.form.wechatShareImg = null
      this.fileList = []
    },
    handleUploadSuccess(res, file) {
      if (res && res.data && res.data.path) {
        this.form.wechatShareImg = res.data.path;
        this.fileList = [{ name: file.name, url: res.data.path }]
      } else if (res && res.url) {
        this.form.wechatShareImg = res.url;
        this.fileList = [{ name: file.name, url: res.url }]
      }
    },
    beforeUpload2(file) {
      console.log(file, 'file');
      let imageUrl = URL.createObjectURL(file);
      const isJPG = file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/gif';
      const isLt2M = file.size / 1024 / 1024 < 3;
      let isHeight = imageUrl.width === 1920 && imageUrl.height === 520;
      if (!isJPG) {
        this.$message.error('上传图片只能是 png/JPG/gif 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 3MB!');
      }
      if (!isHeight) {
        this.$message.error('上传图片尺寸必须为 1920px*520px!');
      }
      return isJPG && isLt2M && isHeight;
    },
    handleRemove2() {
      this.form.coverImg = null
      this.fileList2 = []
    },
    handleUploadSuccess2(res, file) {
      if (res && res.data && res.data.path) {
        this.form.coverImg = res.data.path;
        this.fileList2 = [{ name: file.name, url: res.data.path }]
      } else if (res && res.url) {
        this.form.coverImg = res.url;
        this.fileList2 = [{ name: file.name, url: res.url }]
      }
    }
  }
}
</script>
<style scoped lang="scss">
.meetingEdit {
  padding: 20px;
  width: 1200px;
  margin: 0 auto;
  &-title {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
  }
  &-tag {
    margin-right: 10px;
  }
}
</style>
